<template>
  <div class="login-container">
    <el-card class="login-card" :body-style="{ padding: '40px' }">
      <template #header>
        <div class="card-header">
          <h2>用户登录</h2>
          <p>欢迎回到 AllHome</p>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="authStore.isLoading"
            @click="handleLogin"
          >
            {{ authStore.isLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <div class="form-footer">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" @click="$router.push('/register')">
            还没有账号？立即注册
          </el-link>
        </div>
      </el-form>

      <el-divider>或</el-divider>

      <div class="social-login">
        <el-button size="large" :icon="UserFilled" circle />
        <el-button size="large" :icon="Message" circle />
        <el-button size="large" :icon="Iphone" circle />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, UserFilled, Message, Iphone } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { getAuth } from '@/api/auth/auth'
import type { LoginRequest } from '@/api/models'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 记住我
const rememberMe = ref(false)

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    
    authStore.setLoading(true)
    authStore.clearError()

    // 调用登录API
    const { loginApiV1AuthLoginPost } = getAuth()
    const loginRequest: LoginRequest = {
      username: loginForm.username,
      password: loginForm.password
    }
    
    const response = await loginApiV1AuthLoginPost(loginRequest)
    
    if (response) {
      const userData = {
        id: (response.family_member.id || '1').toString(),
        username: loginForm.username,
        email: response.family_member.email || 'user@example.com',
        full_name: response.family_member.full_name || loginForm.username,
        family_name: response.family_member.family_name || '',
        token: response.access_token,
        role: response.family_member.role || 'user'
      }
      
      authStore.setAuth(userData, userData.token)
      ElMessage.success('登录成功')
      
      // 如果有重定向地址，则跳转到重定向地址
      const redirect = route.query.redirect as string
      router.push(redirect || '/')
    }

  } catch (error) {
    console.error('登录失败:', error)
    authStore.setError('登录失败，请检查用户名和密码')
    ElMessage.error(authStore.error || '登录失败')
  } finally {
    authStore.setLoading(false)
  }
}

// 组件挂载时检查是否已登录
onMounted(() => {
  if (authStore.isAuthenticated) {
    router.push('/')
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    margin: 0 10px;
  }
  
  .card-header h2 {
    font-size: 20px;
  }
  
  .form-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .login-card {
    background: #1a1a1a;
    border-color: #333;
  }
  
  .card-header h2 {
    color: #fff;
  }
  
  .card-header p {
    color: #999;
  }
}
</style>
